package com.xln.furn.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xln.furn.DTO.LoginFormDTO;
import com.xln.furn.been.Furn;
import com.xln.furn.service.FurnService;
import com.xln.furn.service.UserService;
import com.xln.furn.userVO.User;
import com.xln.furn.util.Result;
import com.xln.furn.util.Token;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class LoginController {

    public static ThreadLocal<User> threadLocal = new ThreadLocal<>();

    @Resource
    private UserService userService;
    @Resource
    private FurnService furnService;

    @GetMapping("/login2")
    public String login(){
        return "login";
    }

    @PostMapping("/loginCheck")
    public String loginCheck(User user,
                             HttpSession session,
                             Model model,
                             HttpServletResponse response,
                             @RequestParam(defaultValue = "1",required = false) Integer pageNum,
                             @RequestParam(defaultValue = "5",required = false) Integer pageSize){

        String name = user.getName();
        String password = user.getPassword();
        log.info("用户名：{} 密码：{}", name,password);
        System.out.printf("用户名：%s 密码：%s", name,password);

        User dbuser = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getName, name));

        if (dbuser == null){
            model.addAttribute("error","用户不存在");
            return "login";
        }
        if (!password.equals(dbuser.getPassword())){
            model.addAttribute("error","密码错误");
            return "login";

        }

        // session.setAttribute("user",user);

        Map<String, Object> map = new HashMap<>();
        map.put("userId",dbuser.getId());
        map.put("username",dbuser.getName());
        String jwt = Jwts.builder().signWith(SignatureAlgorithm.HS256, "eHVsaW5pYW4K")
                .addClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 300 * 1000))
                .compact();
        log.info("jwt=== {}",jwt);
        response.setHeader("token",jwt);


        Page<Furn> furnPage = furnService.page(
                new Page<>(pageNum, pageSize)
        );
        model.addAttribute("furnPage",Result.success(furnPage));
        threadLocal.set(dbuser);
        model.addAttribute("user1",dbuser   );

        return "success";

    }

    @GetMapping("/abc")
    public String success(){

        return "abc";
    }
    @PostMapping("/loginCheck2")
    @ResponseBody
    public Result loginCheck2(@RequestBody LoginFormDTO user,
                              HttpSession session,
                              HttpServletResponse response
//                              @RequestParam(defaultValue = "1",required = false) Integer pageNum,
//                              @RequestParam(defaultValue = "5",required = false) Integer pageSize
                            ){

        User dbUser = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getName, user.getName()));
        log.info("用户名：{} 密码：{}", user.getName(),user.getPassword());

        if (dbUser == null){
            return Result.fail(501,"用户不存在");
        }
        if (!user.getPassword().equals(dbUser.getPassword())){
            return Result.fail(502,"密码错误");
        }
//            response.setHeader("token",Jwts.builder().signWith(SignatureAlgorithm.HS256, "eHVsaW5pYW4K")
//                    .addClaims(new HashMap<String, Object>(){{
//                        put("userId",dbUser.getId());
//                        put("username",dbUser.getName());
//                    }})
//                    .setExpiration(new Date(System.currentTimeMillis() + 300 * 1000))
//                    .compact());
        String token = Token.createToken(dbUser.getName(),dbUser.getPassword());
        log.info("token：{}", token);

        return Result.success(token);
    }

}
